import { Table, Button, Image, Popconfirm, message } from 'antd';
import { bannerListApi, removeBannerApi } from '@/api/banner';
import { useEffect, useState } from 'react';

const Index = () => {
  const [dataSource, setDataSource] = useState([]);

  const getList = () => {
    bannerListApi().then((res) => {
      // console.log(res);
      // setDataSource(res.data);
      if (res) {
        const result = res.data.map((item: any, index: number) => {
          return { ...item, key: index + 1 };
        });

        setDataSource(result);
      }
    });
  };

  const confirm = (id: string) => {
    removeBannerApi({ bannerid: id }).then((res) => {
      if (res) {
        message.success(res.message);
        getList();
      }
    });
  };

  const cancel = () => {
    console.log('取消');
  };

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      width: 100,
    },
    {
      title: '图片',
      dataIndex: 'img',
      // render用来渲染标签的
      // 第一个参数是text，就是dataIndex的值
      // 第二个参数是record，表示整一条数据
      render(text: string) {
        return <Image src={text} />;
      },
    },
    {
      title: '链接',
      dataIndex: 'link',
      width: 100,
    },
    {
      title: '提示',
      dataIndex: 'alt',
      width: 100,
    },
    {
      title: '操作',
      dataIndex: 'bannerid',
      render(text: string, record: any) {
        return (
          <Popconfirm
            title="确定要删除?"
            onConfirm={() => confirm(text)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        );
      },
      width: 100,
    },
  ];

  useEffect(() => {
    getList();
  }, []);

  return (
    <div>
      <Table dataSource={dataSource} columns={columns} />;
    </div>
  );
};

export default Index;
